package com.example.financialsystem;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectChangeListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.example.financialsystem.datas.AccountBean;
import com.example.financialsystem.datas.OClassificationBean;
import com.rengwuxian.materialedittext.MaterialEditText;

import org.apache.commons.lang3.StringUtils;

import java.text.DecimalFormat;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import models.Record;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import others.ServerResponse;
import utils.GsonUtil;
import utils.OkHttpCallback;
import utils.OkhttpUtil;

import static com.example.financialsystem.application.MyApplication.getContext;
import static others.Const.IP;
import static others.Const.JSON;
import static others.Const.PORT;
import static others.Const.SUCCESS;
import static others.Tools.ToastShow;
import static utils.GsonUtil.Json2Class;

public class ModifyRecordActivity extends AppCompatActivity {

    @BindView(R.id.modify_number)
    MaterialEditText textNumber;
    @BindView(R.id.first_class)
    TextView textFirstClass;
    @BindView(R.id.second_class)
    TextView textSecondClass;
    @BindView(R.id.class_linear)
    LinearLayout classLinear;
    @BindView(R.id.account)
    TextView textAccount;
    @BindView(R.id.remark)
    EditText editRemark;
    @BindView(R.id.delete_record)
    Button buttonDelete;
    @BindView(R.id.modify_record)
    Button buttonModify;

    //收入分类滚轮
    private OptionsPickerView IClassificationOptions;
    private ArrayList<OClassificationBean> IClassFirstItems = new ArrayList<>();
    private ArrayList<ArrayList<String>> IClassSecondItems = new ArrayList<>();
    //消费分类滚轮
    private OptionsPickerView OClassificationOptions;
    private ArrayList<OClassificationBean> OClassFirstItems = new ArrayList<>();
    private ArrayList<ArrayList<String>> OClassSecondItems = new ArrayList<>();
    //账户滚轮
    private OptionsPickerView accountOptions;
    private ArrayList<AccountBean> accountFirstItems = new ArrayList<>();
    private ArrayList<ArrayList<String>> accountSecondItems = new ArrayList<>();

    DecimalFormat df = new DecimalFormat("#.00");

    private Record record;

    private boolean isModify = false;
    private String firstAccount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_modify_record);
        ButterKnife.bind(this);

        record = (Record)getIntent().getSerializableExtra("record");
        textNumber.setText(df.format(record.getMoney()));
        if (record.getType()==0){
            textNumber.setBaseColor(Color.parseColor("#228b22"));
            textNumber.setTextColor(Color.parseColor("#228b22"));
            textNumber.setPrimaryColor(Color.parseColor("#228b22"));
        }
        textFirstClass.setText(record.getFirstclass());
        textSecondClass.setText(record.getSecondclass());
        firstAccount = record.getFirstaccount();
        textAccount.setText(record.getSecondaccount());
        String remark = record.getRemark();
        if (!StringUtils.isBlank(remark)){
            editRemark.setText(remark);
        }

    }

    @OnClick({R.id.class_linear, R.id.account, R.id.delete_record, R.id.modify_record})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.class_linear:
                if (record.getType()==0){
                    LoadOClassOptionData();
                    InitOClassOptionPicker();
                    OClassificationOptions.show();
                } else {
                    LoadIClassOptionData();
                    InitIClassOptionPicker();
                    IClassificationOptions.show();
                }
                break;
            case R.id.account: {
                LoadAccountOptionData();
                InitAccountOptionPicker();
                accountOptions.show();
                break;
            }
            case R.id.delete_record: {
                String url = "http://" + IP + ":" + PORT + "/portal/record/deleteRecord.do";
                RequestBody requestBody = new FormBody.Builder()
                        .add("recordId",record.getRecordid())
                        .build();
                Request request = new Request.Builder()
                        .url(url)
                        .post(requestBody)
                        .build();
                SendRequest(request);
                break;
            }
            case R.id.modify_record: {
                Record temp = (Record) record.clone();
                temp.setMoney(Double.parseDouble(textNumber.getText().toString()));
                temp.setFirstclass(textFirstClass.getText().toString());
                temp.setSecondclass(textSecondClass.getText().toString());
                temp.setFirstaccount(firstAccount);
                temp.setSecondaccount(textAccount.getText().toString());
                if (record.equals(temp)) {
                    ToastShow("您并未作出任何修改");
                    finish();
                } else {
                    record = temp;
                    String url = "http://" + IP + ":" + PORT + "/portal/record/modifyRecord.do";
                    String jsonData = GsonUtil.class2Json(record);
                    RequestBody requestBody = RequestBody.create(JSON, jsonData);
                    Request request = new Request.Builder()
                            .url(url)
                            .post(requestBody)
                            .build();
                    SendRequest(request);
                }
                break;
            }
        }
    }

    public void SendRequest(Request request){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkhttpUtil.SendRequestWithPost(
                            request,
                            new OkHttpCallback(){
                                @Override
                                public void onFinish(String status, String responseData) {
                                    if (status.equals(SUCCESS)){
                                        ServerResponse serverResponse = Json2Class(responseData);
                                        if (serverResponse.getStatus() == 0){
                                            Looper.prepare();
                                            ToastShow("操作成功");
                                            finish();
                                            Looper.loop();
                                        }else {
                                            Looper.prepare();
                                            ToastShow(serverResponse.getMsg());
                                            Looper.loop();
                                        }
                                    } else {
                                        Looper.prepare();
                                        ToastShow("连接服务器失败,请稍后再试");
                                        Looper.loop();
                                    }
                                }
                            });
                }catch (Exception e){
                    ToastShow("抱歉了亲,我们可能遇到了些麻烦");
                    e.printStackTrace();
                }
            }
        }).run();
    }

    private void LoadAccountOptionData() {
        //选项一
        accountFirstItems.add(new AccountBean(0, "现金", null));
        accountFirstItems.add(new AccountBean(1, "信用卡", null));
        accountFirstItems.add(new AccountBean(2, "金融账户", null));
        accountFirstItems.add(new AccountBean(3, "虚拟账户", null));
        accountFirstItems.add(new AccountBean(4, "投资账户", null));

        //选项二
        ArrayList<String> options2Items_00 = new ArrayList<>();
        options2Items_00.add("现金(CNY)");
        ArrayList<String> options2Items_01 = new ArrayList<>();
        options2Items_01.add("信用卡(CNY)");
        ArrayList<String> options2Items_02 = new ArrayList<>();
        options2Items_02.add("中国银行(CNY)");
        options2Items_02.add("中国建设银行(CNY)");
        options2Items_02.add("中国农业银行(CNY)");
        options2Items_02.add("中国工商银行(CNY)");
        options2Items_02.add("交通银行(CNY)");
        ArrayList<String> options2Items_03 = new ArrayList<>();
        options2Items_03.add("支付宝(CNY)");
        options2Items_03.add("微信钱包(CNY)");
        options2Items_03.add("饭卡(CNY)");
        ArrayList<String> options2Items_04 = new ArrayList<>();
        options2Items_04.add("基金账户(CNY)");
        options2Items_04.add("余额宝(CNY)");
        options2Items_04.add("股票账户(CNY)");

        accountSecondItems.add(options2Items_00);
        accountSecondItems.add(options2Items_01);
        accountSecondItems.add(options2Items_02);
        accountSecondItems.add(options2Items_03);
        accountSecondItems.add(options2Items_04);
        /*数据添加完毕*/
    }

    private void InitAccountOptionPicker() {
        accountOptions = new OptionsPickerBuilder(this,
                new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        //返回的分别是三个级别的选中位置
                        firstAccount = accountFirstItems.get(options1).getPickerViewText();
                        textAccount.setText(accountSecondItems.get(options1).get(options2));
                    }
                })
                .setTitleText("账户")
                .setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0, 1)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(Color.WHITE)
                .setTitleColor(Color.BLACK)
                .setCancelColor(Color.BLACK)
                .setSubmitColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK)
                .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                //.setLabels("省", "市", "区")
                .setOutSideColor(0x00000000) //设置外部遮罩颜色
                .setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
                    @Override
                    public void onOptionsSelectChanged(int options1, int options2, int options3) {
                        firstAccount = accountFirstItems.get(options1).getPickerViewText();
                        textAccount.setText(accountSecondItems.get(options1).get(options2));
                    }
                })
                .build();
        accountOptions.setPicker(accountFirstItems, accountSecondItems);//二级选择器
    }

    private void LoadIClassOptionData() {
        IClassFirstItems.add(new OClassificationBean(0, "职业收入", "描述部分"));
        IClassFirstItems.add(new OClassificationBean(0, "其他收入", "描述部分"));

        ArrayList<String> options2Items_00 = new ArrayList<>();
        options2Items_00.add("工资收入");
        options2Items_00.add("利息收入");
        options2Items_00.add("奖金收入");
        options2Items_00.add("兼职收入");
        options2Items_00.add("投资收入");
        ArrayList<String> options2Items_01 = new ArrayList<>();
        options2Items_01.add("礼金收入");
        options2Items_01.add("中奖收入");
        options2Items_01.add("意外来钱");
        options2Items_01.add("经营所得");

        IClassSecondItems.add(options2Items_00);
        IClassSecondItems.add(options2Items_01);
    }

    private void InitIClassOptionPicker() {
        IClassificationOptions = new OptionsPickerBuilder(this,
                new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        //返回的分别是三个级别的选中位置
                        textFirstClass.setText(IClassFirstItems.get(options1).getPickerViewText());
                        textSecondClass.setText(IClassSecondItems.get(options1).get(options2));
                    }
                })
                .setTitleText("分类")
                .setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0, 1)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(Color.WHITE)
                .setTitleColor(Color.BLACK)
                .setCancelColor(Color.BLACK)
                .setSubmitColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK)
                .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setOutSideColor(0x00000000) //设置外部遮罩颜色
                .setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
                    @Override
                    public void onOptionsSelectChanged(int options1, int options2, int options3) {
                        textFirstClass.setText(IClassFirstItems.get(options1).getPickerViewText());
                        textSecondClass.setText(IClassSecondItems.get(options1).get(options2));
                    }
                })
                .build();
        IClassificationOptions.setPicker(IClassFirstItems, IClassSecondItems);//二级选择器
    }

    private void LoadOClassOptionData() {
        /*
         * 注意：如果是添加JavaBean实体数据，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        //选项1
        OClassFirstItems.add(new OClassificationBean(0, "食品酒水", "描述部分"));
        OClassFirstItems.add(new OClassificationBean(1, "居家物业", "描述部分"));
        OClassFirstItems.add(new OClassificationBean(2, "衣服饰品", "描述部分"));
        OClassFirstItems.add(new OClassificationBean(3, "行车交通", "描述部分"));
        OClassFirstItems.add(new OClassificationBean(4, "交流通讯", "描述部分"));
        OClassFirstItems.add(new OClassificationBean(5, "休闲娱乐", "描述部分"));
        OClassFirstItems.add(new OClassificationBean(6, "学习进修", "描述部分"));
        OClassFirstItems.add(new OClassificationBean(7, "人情往来", "描述部分"));
        OClassFirstItems.add(new OClassificationBean(8, "医疗保障", "描述部分"));
        OClassFirstItems.add(new OClassificationBean(9, "金融保险", "描述部分"));

        //选项2
        ArrayList<String> options2Items_00 = new ArrayList<>();
        options2Items_00.add("🥣早午晚餐");
        options2Items_00.add("烟酒茶");
        options2Items_00.add("水果零食");
        ArrayList<String> options2Items_01 = new ArrayList<>();
        options2Items_01.add("日常用品");
        options2Items_01.add("水电煤气");
        options2Items_01.add("房租");
        options2Items_01.add("物业管理");
        options2Items_01.add("维修保养");
        ArrayList<String> options2Items_02 = new ArrayList<>();
        options2Items_02.add("衣服裤子");
        options2Items_02.add("鞋帽包包");
        options2Items_02.add("化妆饰品");
        ArrayList<String> options2Items_03 = new ArrayList<>();
        options2Items_03.add("公共交通");
        options2Items_03.add("打车租车");
        options2Items_03.add("私家车费用");
        ArrayList<String> options2Items_04 = new ArrayList<>();
        options2Items_04.add("手机费");
        options2Items_04.add("上网费");
        options2Items_04.add("邮寄费");
        ArrayList<String> options2Items_05 = new ArrayList<>();
        options2Items_05.add("运动健身");
        options2Items_05.add("腐败聚会");
        options2Items_05.add("休闲玩乐");
        options2Items_05.add("宠物宝贝");
        options2Items_05.add("旅游度假");
        ArrayList<String> options2Items_06 = new ArrayList<>();
        options2Items_06.add("书报杂志");
        options2Items_06.add("培训进修");
        ArrayList<String> options2Items_07 = new ArrayList<>();
        options2Items_07.add("送礼请客");
        options2Items_07.add("孝敬家长");
        options2Items_07.add("还人钱财");
        options2Items_07.add("慈善捐款");
        ArrayList<String> options2Items_08 = new ArrayList<>();
        options2Items_08.add("药品费");
        options2Items_08.add("保健费");
        options2Items_08.add("美容费");
        options2Items_08.add("治疗费");
        ArrayList<String> options2Items_09 = new ArrayList<>();
        options2Items_09.add("银行手续");
        options2Items_09.add("投资亏损");
        options2Items_09.add("按揭还贷");
        options2Items_09.add("消费税收");
        options2Items_09.add("赔偿罚款");

        OClassSecondItems.add(options2Items_00);
        OClassSecondItems.add(options2Items_01);
        OClassSecondItems.add(options2Items_02);
        OClassSecondItems.add(options2Items_03);
        OClassSecondItems.add(options2Items_04);
        OClassSecondItems.add(options2Items_05);
        OClassSecondItems.add(options2Items_06);
        OClassSecondItems.add(options2Items_07);
        OClassSecondItems.add(options2Items_08);
        OClassSecondItems.add(options2Items_09);
        /*--------数据源添加完毕---------*/
    }

    private void InitOClassOptionPicker() {//条件选择器初始化

        /**
         * 注意 ：如果是三级联动的数据(省市区等)，请参照 JsonDataActivity 类里面的写法。
         */

        OClassificationOptions = new OptionsPickerBuilder(this,
                new OnOptionsSelectListener() {
                    @Override
                    public void onOptionsSelect(int options1, int options2, int options3, View v) {
                        //返回的分别是三个级别的选中位置
                        textFirstClass.setText(OClassFirstItems.get(options1).getPickerViewText());
                        textSecondClass.setText(OClassSecondItems.get(options1).get(options2));
                    }
                })
                .setTitleText("分类")
                .setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0, 1)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(Color.WHITE)
                .setTitleColor(Color.BLACK)
                .setCancelColor(Color.BLACK)
                .setSubmitColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK)
                .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                //.setLabels("省", "市", "区")
                .setOutSideColor(0x00000000) //设置外部遮罩颜色
                .setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
                    @Override
                    public void onOptionsSelectChanged(int options1, int options2, int options3) {
                        textFirstClass.setText(OClassFirstItems.get(options1).getPickerViewText());
                        textSecondClass.setText(OClassSecondItems.get(options1).get(options2));
                    }
                })
                .build();

//        pvOptions.setSelectOptions(1,1);
        /*pvOptions.setPicker(options1Items);//一级选择器*/
        OClassificationOptions.setPicker(OClassFirstItems, OClassSecondItems);//二级选择器
        /*pvOptions.setPicker(options1Items, options2Items,options3Items);//三级选择器*/
    }

}
